package com.shujia.flink.core

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

object Demo6CheckPoint {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
     * 开启checkpoint
     * 需要将代码打包上传到集群运行
     *
     */

    // 每 10000ms 开始一次 checkpoint
    env.enableCheckpointing(10000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    /**
     * 状态后端：保存状态的位置
     *
     */

    //env.setStateBackend(new HashMapStateBackend())

    //增量快照
    env.setStateBackend(new EmbeddedRocksDBStateBackend(true))
    //将状态保存到hdfs中
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/file/checkpoint")


    val linesSource: KafkaSource[String] = KafkaSource
      .builder[String]
      .setBootstrapServers("master:9092")
      .setTopics("checkpoint")
      .setGroupId("asdasdasasd")
      .setStartingOffsets(OffsetsInitializer.earliest)
      .setValueOnlyDeserializer(new SimpleStringSchema())
      .build


    //读取kafka中数据
    val linesDS: DataStream[String] = env.fromSource(linesSource, WatermarkStrategy.noWatermarks(), "Kafka Source")

    val kvDS: DataStream[(String, Int)] = linesDS.flatMap(_.split(",")).map((_, 1))

    val countDS: DataStream[(String, Int)] = kvDS.keyBy(_._1).sum(1)

    countDS.print()

    env.execute()


    /**
     * 初次提交任务
     * flink run -t yarn-per-job -c com.shujia.flink.core.Demo6CheckPoint flink-1.0.jar
     *
     * 任务失败重启，从checkpoint路径恢复任务
     *
     * flink run -t yarn-per-job -c com.shujia.flink.core.Demo6CheckPoint -s hdfs://master:9000/file/checkpoint/ee6762dd56a9cfae04b4629969ff3c16/chk-4 flink-1.0.jar
     */

  }

}
